<?php

namespace app\admin\controller;

use app\AdminBaseController;

class News extends AdminBaseController
{
    public function index(){
        if($this->request->isAjax()){
            $rows = $this->request->param('rows',10,'intval');
            $res = \app\model\Article::where([])->order('id desc')->paginate($rows,false);

            return json(['total'=>$res->total(),'rows'=>$res->items()]);
        } else {
            return view();
        }
    }

    public function add(){
        if($this->request->isPost()){

            $params = $this->request->post();

            preg_match('/<img.+src="(?<url>[^"]+)"/i', $params['con'], $matches);
            $pp = isset($matches['url']) ? $matches['url'] : '/static/assets/images/empty.png';
            $thumb = substr($pp,3);
            $title = isset($params['title']) ? $params['title'] :'';
            $author = isset($params['author']) ? $params['author'] :'';
            $category_id = isset($params['category_id']) ? intval($params['category_id']) :'';

            $model = new \app\model\Article();
            $model->title = $title;
            $model->author = $author;
            $model->category_id = $category_id;
            $model->thumb = $thumb;
            $model->created_at = date('Y-m-d H:i:s',time());
            $model->save();

            if(!$model->isEmpty()){
                $aModel = new \app\model\ArticleContent();
                $aModel->article_id = $model->id;
                $aModel->created_at = date('Y-m-d H:i:s',time());
                $aModel->txt = $params['con'];
                $aModel->save();

                return json(['code'=>0,'message'=>'发布成功']);
            }
        }

    }


}